package pl.koziolekweb.maven.plugins;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

/**
 * Goal which touches a timestamp file.
 * 
 * @goal removeCss
 * 
 * @phase process-resources
 */
public class RemoveCss extends AbstractMojo {

	/**
	 * Location of the source file.
	 * 
	 * @parameter
	 * @required
	 */
	private File source;

	/**
	 * Location of the target file. If empty then target equals source.
	 * 
	 * @optional
	 */
	private File target;

	public void execute() throws MojoExecutionException {
		if (source == null || !source.exists()) {
			getLog().error(
					"Sorry, but source file does not exist. Source is: "
							+ source);
			return;
		}
		if (target == null) {
			target = source;
		}
		try {
			getLog().info("Start removing CSS coments");
			remove();
			getLog().info("All coments removed succesfuly");
		} catch (IOException e) {
			new MojoExecutionException("Sorry removing fail!", e);
		}
	}

	private void remove() throws IOException {
		Reader reader = new FileReader(source);
		int i;
		String fileString = "";
		while ((i = reader.read()) > 0) {
			fileString += (char) i;
		}
		fileString = fileString.replaceAll("\n", ""); // New lines
		fileString = fileString.replaceAll("\t", ""); // tabs
		fileString = fileString.replaceAll("\\s{2,}", ""); // many spacen
		fileString = fileString.replaceAll("\\s\\{", "{"); // spaces before {
		fileString = fileString.replaceAll(":\\s", ":"); // spaces after :
		fileString = fileString.replaceAll("/\\**[^\\*]*\\**/", "");// CSS
		// multiline
		// comments
		Writer writer = new FileWriter(target);
		writer.write(fileString);
		writer.flush();
	}
}
